//
//  converterViewController.m
//  converter
//
//  Created by klamoree on 9/26/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "converterViewController.h"

@implementation converterViewController

@synthesize annuityLabel, annuityControl, calculateFV, calculatePV, viewer, num, ir, pv, pmnt, fv, infoButton, closeInfo;

- (void)dealloc
{
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    UITapGestureRecognizer *gr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)];
//    [[self view] addGestureRecognizer:gr];
//    [gr release];
    num.delegate = self;
    ir.delegate = self;
    pv.delegate = self;
    pmnt.delegate = self;
    fv.delegate = self;
    
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(IBAction) doFVButton {
    
    [self hideKeyboard];
    
    float numPayments = [num.text floatValue];
    float interestRate = [ir.text floatValue];
    interestRate = interestRate/100.00;
    float payment = [pmnt.text floatValue];
    float newFV;
    
    float presentValue = [pv.text floatValue];
    
    switch (annuityControl.selectedSegmentIndex) {
        default:
            //annuity due
            for(int i=0; i<numPayments; i++) {
                presentValue = presentValue*(1+interestRate) + payment;
                
            }
            newFV = presentValue;
            fv.text = [NSString stringWithFormat:@"%f", newFV];
            
            break;
        case 1:
            //annuity immediate

            for(int i=0; i<numPayments; i++) {
                presentValue = (1+interestRate)*(presentValue + payment);
                
            }
            newFV = presentValue;
            fv.text = [NSString stringWithFormat:@"%f", newFV];
            
            break;
    }
}

-(IBAction) doPVButton {
    
    [self hideKeyboard];
    
    double numPayments = [num.text doubleValue];
    double interestRate = [ir.text doubleValue];
    interestRate = interestRate/100.00;
    double payment = [pmnt.text doubleValue];
    double newPV;
    
    float futureValue = [fv.text floatValue];
    
    switch (annuityControl.selectedSegmentIndex) {
        default:
            //annuity due
            for(int i=0; i<numPayments; i++) {
                futureValue = (futureValue + payment)/(1+interestRate);
                
            }
            newPV = futureValue;
            pv.text = [NSString stringWithFormat:@"%f", newPV];
            
            break;
        case 1:
            //annuity immediate
            for(int i=0; i<numPayments; i++) {
                futureValue = futureValue/(1+interestRate) + payment;
                
            }
            newPV = futureValue;
            pv.text = [NSString stringWithFormat:@"%f", newPV];
            
            break;
    }
    
    
}

//Method used to get index of a character
-(int)getIndexOf:(char)c:(NSString*)stringS:(int)start {
    
    for(int i=start;i<stringS.length;i++) {
        if(c == [stringS characterAtIndex:i]) {
            return i;
        }
    }
    return -1;
}

-(IBAction) doInfoButton {
    //Show info view
    [self presentModalViewController:ivc animated:YES];
}

-(IBAction) doCloseInfoButton {
    //Hide info view
    [self dismissModalViewControllerAnimated:YES];
}

-(IBAction)segmentedValueChange {
    //Controls annuityLabel based on segmented control value.
    switch (annuityControl.selectedSegmentIndex) {
        default: [annuityLabel setText:@"Annuity Due"]; break;
        case 1: [annuityLabel setText:@"Annuity Immediate"]; break;
    }
}

-(BOOL)textFieldShouldEndEditing:(UITextField *)textField {
    
    //These represent the only valid characters
    NSCharacterSet *acceptedInput =
    [[NSCharacterSet characterSetWithCharactersInString:@"1234567890-."] invertedSet];
    
    if ([[textField.text componentsSeparatedByCharactersInSet:acceptedInput] count] > 1) {
        //If there is anything but the valid characters, then reveal an error and reset the textField.
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Invalid character" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [alert show];
        [alert release];
        textField.text=@"0";
        
        
    }
    
    int neg = [self getIndexOf:'-':textField.text:0];
    int dec = [self getIndexOf:'.':textField.text:0];
    int decCheck = [self getIndexOf:'.':textField.text:dec+1];
    
    if(neg > 0 || decCheck!=-1) {
        //If the negative sign is anywhere but the beginning or if there is two decimal points, reset the textField
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Invalid character position" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [alert show];
        [alert release];
        textField.text=@"0";
    }
    
    if (dec==[textField.text length]-1) {
        //If a string ends in a decimal, add 0 to the end of it.
        textField.text= [NSString stringWithFormat:@"%@%@", textField.text, @"0"];
    }
    
    return YES;
}

//Once the done button is hit from a textfields keyboard, hide the keyboard.
-(BOOL)textFieldShouldReturn:(UITextField *)textField {
    [self hideKeyboard];
    return YES;
}

//Hides all open keyboards
-(void)hideKeyboard {
    [num resignFirstResponder];
    [ir resignFirstResponder];
    [pv resignFirstResponder];
    [pmnt resignFirstResponder];
    [fv resignFirstResponder];
    
    // include other fields
}

     


@end
